﻿using Spire.Pdf;
using Spire.Pdf.Graphics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SuperKit
{
    class PDFClear : CommandExecutor {
        public PDFClear(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath) {

        }

        public List<FileInfo> ClearList { get; private set; }
        public override void Execute() {
            base.Execute();
            ClearList = new List<FileInfo>();
            GetAllFiles(new DirectoryInfo(FilePath), ClearList, Kit.PDF_EXTS);
            Thread t = new Thread(StartClear);
            t.Start();
        }

        private void StartClear() {
            foreach (var i in ClearList) {
                Clear(i);
            }
            End();
        }

        private void Clear(FileInfo file) {
            int deleted = 0;
            PdfDocument doc = new PdfDocument(file.FullName);
            List<PdfPageBase> list = new List<PdfPageBase>();
            foreach (PdfPageBase i in doc.Pages) {
                if (IsClear(i)) {
                    list.Add(i);
                    deleted++;
                    //
                } else {
                    //Flush("Size is:{0}, Passed", i.Size);
                }
                ///Flush(i.ToString());
            }
            foreach (var i in list) {
                doc.Pages.Remove(i);
            }
            doc.SaveToFile(GetNewFile(file));
            doc.Close();
            Flush("Clear:{0}, Deleted:{1}", file.Name, deleted);

        }

        private string GetNewFile(FileInfo file) {
            return Path.Combine(FilePath, "(Modify)", Path.GetFileNameWithoutExtension(file.Name) + file.Extension);
        }

        private bool IsClear(PdfPageBase page) {
            var s = page.Size;
            if (s.Width == 1200 && s.Height == 1200) {
                return true;
            }
            if (s.Width == 1128 && s.Height == 1461) {
                return true;
            }
            if (s.Width == 544 && s.Height == 583) {
                return true;
            }
            if (s.Width == 750 && s.Height == 1344) {
                return true;
            }
            return false;
        }
    }
}
